<script setup lang="ts">
import { getDishesList, addDishes, updateDishes, deleteDishes } from '@/api/dishes';
import type { Dishes, DishesSearchForm } from '@/api/dishes/type';
import { ElMessage, ElMessageBox, type Action, type FormInstance, type FormRules, type UploadProps, type UploadUserFile } from 'element-plus';
import { nextTick, reactive, ref, toRefs } from 'vue';
import { typeById } from '@/api/ingredients';
import type { Ingredient } from '@/api/ingredients/types';
import { useTokenStore } from '@/stores/useTokenStore';
const tokenStore = useTokenStore()
const base_url = import.meta.env.VITE_APP_BASE_API

/* 主食  辅食 调料的获取 */
const mainList = ref<Ingredient[]>([])
const minorList = ref<Ingredient[]>([])
const seasoningList = ref<Ingredient[]>([])
const fetchAllIngredients = async () => {
  mainList.value = await typeById(1)
  minorList.value = await typeById(2)
  seasoningList.value = await typeById(3)
}
/* 菜品 分页+模糊 */
const searchFormRef = ref<FormInstance>()
const searchForm = reactive<DishesSearchForm>({
  pageNum: 1,
  pageSize: 5,
  name: ''
})
const { pageNum, pageSize, name } = toRefs(searchForm)
const total = ref(0)
const dishesList = ref<Dishes[]>([])
const queryDishes = (currenPageNum = 1) => {

  pageNum.value = currenPageNum

  getDishesList(searchForm)
    .then(data => {
      dishesList.value = data.rows
      total.value = data.total
    })
}
/* ====添加修改=== */
const dishesDialogVisible = ref(false)
const dishesDialogTitle = ref('添加菜品操作')
const dishesFormRef = ref<FormInstance>()
const dishesForm = ref<Dishes>({
  name: '',
  url: '',
  main: '',
  mainNum: 0,
  minor: '',
  minorNum: 0,
  seasoning: '',
  seasoningNum: 0,
  description: ''
})
const dishesFormRules = ref<FormRules>({
  name: [{ required: true, message: '请输入菜品名' }],
  url: [{ required: true, message: '请传入图片' }],
  main: [{ required: true, message: '请选择主食材' }],
  mainNum: [{ required: true, message: '请填写主食材数量' }],
  minor: [{ required: true, message: '请选择副食材' }],
  minorNum: [{ required: true, message: '请填写副食材数量' }],
  seasoning: [{ required: true, message: '请选择调料' }],
  seasoningNum: [{ required: true, message: '请填写副食材数量' }],
  description: [{ required: true, message: '请填写菜品描述' }]
})


const handleEdit = (dishes: Dishes) => {
  dishesDialogVisible.value = true
  nextTick(() => {
    dishesForm.value = { ...dishes }
    dishesFormRef.value?.resetFields()
    fileList.value = [{ name: dishes.url, url: base_url + dishes.url }]
  })
}
const handleAdd = () => {
  dishesDialogVisible.value = true
  nextTick(() => {
    fileList.value = []

    dishesForm.value = {
      name: '',
      url: '',
      main: '',
      mainNum: 0,
      minor: '',
      minorNum: 0,
      seasoning: '',
      seasoningNum: 0,
      description: ''
    }

    dishesFormRef.value?.resetFields()
  })
}

/* 表单重置 */
const reset = () => {
  searchFormRef.value?.resetFields()
  queryDishes()
}

/* 提交操作 */
const doHandle = () => {
  dishesFormRef.value?.validate(async (valid) => {
    if (valid) {

      if (!dishesForm.value.id) {
        await addDishes(dishesForm.value)

        pageNum.value = 1
      } else {
        await updateDishes(dishesForm.value)
      }
      ElMessage.success('操作成功')
      dishesDialogVisible.value = false
      queryDishes(pageNum.value)
    }
  })
}


/* =====删除菜品====== */
const del = (id: any) => {
  ElMessageBox.confirm(
    '确定要删除菜品吗?',
    '菜品删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消删除',
      type: 'warning',
    }
  )
    .then(async () => {
      await deleteDishes(id)
      queryDishes()
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      })
    })
}





/* ====文件上传操作===== */
/* 文件集合 */
const fileList = ref<UploadUserFile[]>()
/* 文件大小 */
const fileSize = ref<number>(1)
/* 文件个数 */
const fileTotal = ref(1)
/* EXCEED */
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.error(`上传不能超过${fileSize}个`)
}
/* BEFOER UPLOAD  */
const handleBeforeUpload: UploadProps['beforeUpload'] = (file: File) => {
  const isPng = file.type == 'image/png'
  const isJpg = file.type == 'image/jpeg'
  if (isPng || isJpg) {
    if (file.size / 1024 / 1024 > fileSize.value) {
      ElMessage.error('请上传小于1MB的文件!')
      return false
    }
  } else {
    ElMessage.error('请上传JPEG或者PNG格式图片')
    return false
  }
}
/* ON SUCCESS */
const handleSuccess: UploadProps['onSuccess'] = (resp, uploadFile) => {
  dishesForm.value.url = resp.data
  dishesFormRef.value?.validateField('url')
}
/* ON REMOVE */
const handleRemove: UploadProps['onRemove'] = (resp, uploadFile) => {
  dishesForm.value.url = ''
  dishesFormRef.value?.validateField('url')
}
/* ====文件上传操作===== */



/* 所有需要created生命周期加载的数据 */
queryDishes()
fetchAllIngredients()
</script>

<template>
  <div class="app-container">
    <!-- 模糊查询 -->
    <div class="app-searchform">
      <el-form 
      @submit.native.prevent
      @keyup.enter="queryDishes()" 
      ref="searchFormRef" :model="searchForm" inline>

        <!-- 菜品名 -->
        <el-form-item label="菜品名" prop="name">
          <el-input  v-model="searchForm.name"></el-input>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" plain icon="Search" @click="queryDishes()">搜索</el-button>
          <el-button type="info" plain icon="Refresh" @click="reset">重置</el-button>
          <el-button type="success" plain icon="Plus" @click="handleAdd">添加</el-button>
        </el-form-item>
      </el-form>
    </div>


    <!-- 数据展示 -->
    <div class="app-table" style="display:flex;flex:1;margin:10px;">
      <el-table style="height:100%;width:100%;" border stripe :data="dishesList">
        <el-table-column  align="center" label="序号" type="index" width="70px" />
        <el-table-column  align="center" label="菜品名称" prop="name" />
        <el-table-column  align="center" label="主要食材">
          <template #default="scope">
            {{ scope.row.mainName ? scope.row.mainName : '当前没有主菜' }}
          </template>
        </el-table-column>
        <el-table-column  align="center" label="辅助食材">
          <template #default="scope">
            {{ scope.row.minorName ? scope.row.minorName : '当前没有辅助食材' }}
          </template>
        </el-table-column>
        <el-table-column  align="center" label="辅助食材">
          <template #default="scope">
            {{ scope.row.seasoningName ? scope.row.seasoningName : '当前没有配料' }}
          </template>
        </el-table-column>
        <el-table-column  align="center" label="菜品图片">
          <template #default="scope">
            <el-image :src="base_url + scope.row.url" style="width:100px;height:80px"
              :preview-src-list="[base_url + scope.row.url]" preview-teleported></el-image>
          </template>
        </el-table-column>
        <el-table-column  align="center" label="操作">
          <template #default="scope">
            <el-button type="success" icon="Edit" :circle="true" @click="handleEdit(scope.row)" />
            <el-button type="danger" icon="Delete" :circle="true" @click="del(scope.row.id)" />
          </template>
        </el-table-column>
      </el-table>
    </div>


    <!-- 分页 -->
    <el-pagination class="app-pagination" background layout="total,sizes,pre,pager,next,jumper"
      v-model:current-page="pageNum" v-model:page-size="pageSize" 
      :page-sizes="[1,5,10,15]" :total="total"
      @current-change="queryDishes" @size-change="queryDishes()"></el-pagination>
  </div>

  <!-- dialog -->
  <el-dialog :title="dishesDialogTitle" width="600px" v-model="dishesDialogVisible" :close-on-click-modal="false">
    <el-form ref="dishesFormRef" :model="dishesForm" :rules="dishesFormRules">
      <el-form-item label="菜品名" prop="name">
        <el-input style="margin-left:15px" placeholder="请填写菜品名" v-model="dishesForm.name"></el-input>
      </el-form-item>
      <el-form-item label="菜品图片" prop="url">
        <el-upload
        :headers="{'Authorization':tokenStore.getToken}"
        v-model:file-list="fileList" :action="base_url + '/dishes-service/upload/image'" :limit="fileTotal"
          :on-remove="handleRemove" :on-exceed="handleExceed" :before-upload="handleBeforeUpload"
          :on-success="handleSuccess" list-type="picture">
          <el-button type="primary">点击上传图片</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500kb
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <div style="display:flex">
        <el-form-item style="width:180px" label="主食材" prop="main">
          <el-select style="margin-left:15px" v-model="dishesForm.main">
            <el-option  v-for="item in mainList" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left:15px" label="主食材数量">
          <el-input-number v-model="dishesForm.mainNum"></el-input-number>
        </el-form-item>
      </div>
      <!-- 副食材 -->
      <div style="display:flex">
        <el-form-item style="width:180px" label="副食材" prop="minor">
          <el-select style="margin-left:15px" v-model="dishesForm.minor">
            <el-option v-for="item in minorList" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left:15px" label="副食材数量">
          <el-input-number v-model="dishesForm.minorNum"></el-input-number>
        </el-form-item>
      </div>
      <!-- 调料 -->
      <div style="display:flex">
        <el-form-item style="width:180px;" label="调味料" prop="seasoning">
          <el-select style="margin-left:14px" v-model="dishesForm.seasoning">
            <el-option v-for="item in seasoningList" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left:15px" label="调味料数量">
          <el-input-number v-model="dishesForm.seasoningNum"></el-input-number>
        </el-form-item>
      </div>
      <el-form-item label="菜品描述" prop="description">
        <el-input type="textarea" v-model="dishesForm.description" placeholder="请输入菜品描述"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="doHandle">提交菜品</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>
:deep(.el-upload-list__item) {
  transition: none !important;
}



</style>